package com.newx.file.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;

import java.io.InputStream;

/**
 * @Classname OssConfigUtils
 * @Description TODO
 * @Date 2023/11/30 17:51
 * @Created by yxl
 */
public class AliyunOssUtil {

    /**
     * 上传文件到阿里云
     * @param inputStream 待上传文件流
     * @param accessKeyId 阿里云 oss 公钥
     * @param accessKeySecret 阿里云 oss 私钥
     * @param endpoint 阿里云资源访问url(不包含具体资源名称部分)
     * @param endpoint 阿里云 oss 站点
     * @param bucketName 阿里云 oss bucket 名称
     * @param fileUrl 文件存储路径 -》 /aaa/bbb/ccc.txt
     * @return
     */
    public static String uploadAliyunFileConfig(InputStream inputStream, String accessKeyId,
                                              String accessKeySecret, String oosUrl,String endpoint,
                                              String bucketName, String fileUrl){
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        DefaultCredentialProvider credentialsProvider = CredentialsProviderFactory.newDefaultCredentialProvider(accessKeyId, accessKeySecret);
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileUrl, inputStream);
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            return oosUrl + fileUrl;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
            throw new RuntimeException(oe.getErrorMessage());
        } catch (Exception ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
            throw new RuntimeException(ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
